#encoding: utf-8
require_relative "../../app/models/gps"
class MotorcadeMapsController < ApplicationController

  before_filter :clean_page, :only => [:query_vehicles]

  def index
    begin
      conditions = {}
      conditions = init_identity_condition(conditions)
      vehicles = Vehicle.select("distinct groups").where(conditions).all
      @groups = vehicles.collect { |vehicle| vehicle.groups }

      conditions = {}
      conditions = init_identity_condition(conditions)

      vehicle_no = params[:vehicle_no]
      conditions[:vehicle_no] = '%'+vehicle_no+'%' if not_empty?(vehicle_no)

      driver_name = params[:driver_name]
      conditions[:driver_name] = '%'+driver_name+'%' if not_empty?(driver_name)
      group = params[:group]
      conditions[:groups] = remove_vague_feature(group) if not_empty?(group)
      destination = params[:destination]
      conditions[:destination] = '%'+destination+'%' if not_empty?(destination)

      @vehicles = Vehicle.query_vehicles(conditions, params[:page]).all
     #查询车辆最新的gps坐标，渲染到模版以便定位使用
      mc = Opal::Mc::Mc.new("VEHICLE_MC")
      @gpses = {}
      @vehicles.each do |vehicle|
        @gpses[vehicle.vehicle_no] = mc.get(vehicle.vehicle_no)
        logger.debug mc.get(vehicle.vehicle_no).methods
      end
      notice = "查询成功"
    rescue Exception => e
      notice = "系统异常，稍后再试"
      logger.error "#{e.class}:#{e.message}"
      render :json => {:notice => notice, :html => ""}
      return
    end
    respond_to do |format|
      format.html { render :layout => "common" } # index.html.erb
      format.json { render :json => {:notice => notice, :html => render_to_string(:template => '/utils/_vehicles.html.erb')} }
    end
  end

  def vehicles_in_area
    begin
      lng_range = [params[:lng_min], params[:lng_max]]
      lat_range = [params[:lat_min], params[:lat_max]]
      gps_range = {}
      notice = "页面异常，刷新再试"
      if (is_number?(lng_range[0]) and is_number?(lng_range[1]) and is_number?(lat_range[0]) and is_number?(lat_range[1]))
        lng_min = str2number lng_range[0]
        lng_max = str2number lng_range[1]
        lat_min = str2number lat_range[0]
        lat_max = str2number lat_range[1]
        if lng_max >= lng_min and lat_max >= lat_min
          lng_range = [lng_min*1000000, lng_max*1000000]
          lat_range = [lat_min*1000000, lat_max*1000000]
          gps_range[:lng] = lng_range
          gps_range[:lat] = lat_range
          @vehicles = current_user.biz_unit.vehicle_in_range_from_mc gps_range #hash格式:{车号=>gpsObJ}
          notice = "查询成功"
          notice = "查询成功，没有符合条件的车辆" if @vehicles.empty?
          status = "success"
        end
      end
    rescue Exception => e
      logger.info e.message
      notice = "系统异常，稍后再试"
    end
    render :json => {:vehicles => @vehicles, :notice => notice, :status => status}
  end


  def vehicle_history
    vehicle_no = params[:vehicle_no]
    start_time = params[:start_time]
    end_time = params[:end_time]

    if not_empty?(vehicle_no) and (start_time <= end_time)
      #验证车辆是不是该车队的
      conditions = {}
      conditions[:vehicle_no] = vehicle_no
      conditions = init_identity_condition(conditions)
      vehicle_count = Vehicle.where(conditions).all.size
      if vehicle_count > 0
        conditions[:start] = start_time
        conditions[:end] = end_time
        @gps_history = GpsHistory.query_gps_history_in_period conditions
        if @gps_history.size > 0
          notice = "查询成功"
          status = "success"
        else
          notice = "没有该车的历史轨迹"
        end
      else
        notice = "非法操作，不允许查询非本车队车辆信息"
      end
    else
      notice = "页面异常，请刷新后再试"
    end
    render :json => {:status =>status, :notice => notice, :gps_history=> @gps_history}
  end


  private
  def is_number?(str)
    return str.to_f.to_s == str ? true : false
  end

  def str2number(str)
    return str.to_f
  end

  def not_empty?(str)
    if str
      if str.strip != ""
        return true
      end
    end
    return false
  end

  #去除查询字符串中的%，防止用户非法操作
  def remove_vague_feature(str)
    if str
      if str.include?('%')
        return str.delete '%'
      end
      return str
    end
    return nil
  end
end
